package com.stu.dcxy.juc;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @Classname ThreadLocalDemo
 * @Version 1.0.0
 * @Date 2022/3/11 10:56
 * @Created by yd
 */
class MovitTicket {
    int number = 50;

    public synchronized void saleTicket() {
        if (number > 0) {
            System.out.println(Thread.currentThread().getName() + "\t卖出第" + (number--));
        } else {
            System.out.println("卖光了");
        }
    }
}


class House {
    //初始化|线程版map
    ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

    public void saleHouse() {
        Integer integer = threadLocal.get();
        ++integer;
        threadLocal.set(integer);
    }

}

public class ThreadLocalDemo {
    public static void main(String[] args) {
        // MovitTicket movitTicket = new MovitTicket();
        // for (int i = 0; i < 3; i++) {
        //     for (int j = 0; j < 20; j++) {
        //         movitTicket.saleTicket();
        //     }
        // }

        House house = new House();
        new Thread(() -> {
            try {
                for (int i = 0; i < 3; i++) {
                    house.saleHouse();
                }
                System.out.println(Thread.currentThread().getName() + "\t卖出" + house.threadLocal.get());
            } finally {
                house.threadLocal.remove();
            }
        }).start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 3; i++) {
                    house.saleHouse();
                }
                System.out.println(Thread.currentThread().getName() + "\t卖出" + house.threadLocal.get());
            } finally {
                house.threadLocal.remove();
            }
        }).start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    house.saleHouse();
                }
                System.out.println(Thread.currentThread().getName() + "\t卖出" + house.threadLocal.get());
            } finally {
                house.threadLocal.remove();
            }
        }).start();
        try {
            TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(5));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
